#coding=utf-8
#coding=utf-8
from datetime import datetime,timedelta
import logging
import os
import re
import string
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import images
from content import AutoCode, ContentClass, ReplyContent
from control import getTimeIndex
from google.appengine.api import urlfetch
import methods
from models import Images, Setting
from photoLib import PhotoLib, PhotoLib_Photo
from tool import filterNone

__author__ = 'wj'

class PublicPage(webapp.RequestHandler):
  def render(self, template_file, template_value):
      path = os.path.join(os.path.dirname(__file__), template_file)
      self.response.out.write(template.render(path, template_value))

class GetRSS(PublicPage):
    def get(self):
        contentlist=db.GqlQuery("SELECT * FROM ContentClass WHERE code > 'a1' AND code <'a1-9' AND level='3' AND status='1' ORDER BY code ASC")
        RSSList=[]
        for c in contentlist:
            if c.code[-1]=='R' and c.status=='1':
                RSSList.append(c)
        for r in RSSList:
            self.response.out.write('%s' % r.code.replace('\r','').replace('\n','').encode('utf-8'))
            self.response.out.write('$$')
            self.response.out.write("%s" % r.content.replace('\r','').replace('\n','').encode('utf-8'))
            self.response.out.write('$$')
            self.response.out.write('\r\n')
        return

class ChangeRSS(PublicPage):
    def get(self):
        self.response.out.write('0')
def getTmpLib():
    tmp='Tmp'
    lib=PhotoLib().all().filter('photoLibName =',tmp).fetch(1)
    if len(lib)==0:
        lib=PhotoLib()
        lib.photoLibCode=string.atoi(getTimeIndex())
        lib.photoLibName=tmp
        lib.put()
    else:
        lib=lib[0]
    return lib

class downloadpic(PublicPage):
    def __init__(self):
        self.urls=[]
    def get(self):
        lib=getTmpLib()
#        db.delete(db.GqlQuery("SELECT * FROM ContentClass WHERE lastUpdateTime < :1 AND maincode='a1' AND level = '4'",datetime.now()+timedelta(hours=-48)).fetch(10))
#        db.delete(Images().all().filter('updataTime <',datetime.now()+timedelta(hours=-48)).fetch(10))
        imglist=Images().all().filter('updataTime <',datetime.now()).filter('isDown',False).order('updataTime').fetch(20)
        website=Setting().all().fetch(1)
        if 0 == len(website):
            w=Setting()
            w.webSite='http://dbphoto225.appspot.com'
            w.put()
            website.append(w)
        web=website[0]
        for img in imglist:
            if hasattr(img,'appname') and img.appname=='weibo':
                self.urls.append((img,web.weiboSite+'/img?img_id='+str(img.otherId)))
            else:
                self.urls.append((img,web.webSite+'/img?img_id='+str(img.otherId)))
        self.searchPic()

    def searchPic(self):
        rpcs=[]
        for img,url in self.urls:
            rpc=urlfetch.create_rpc(deadline=10)
            rpc.callback=self.rpc_callback(rpc,img,url)
            urlfetch.make_fetch_call(rpc, url,  headers={'User-Agent':'Mozilla/5.0'},follow_redirects=True)
            rpcs.append(rpc)
        for rpc in rpcs:
            rpc.wait()
#        Search.saveBook(self.bookMaps)
    def rpc_callback(self,rpc,img,url):
        return lambda:self.handle_result(rpc,img,url)
    def handle_result(self,rpc,img,url):
        try:
            result=rpc.get_result()
            if result.status_code ==200:
                img.bf=db.Blob(result.content)
                img.isDown=True
                img.put()

            elif result.status_code ==404:
                p=PhotoLib_Photo().all().filter('photoCode =',img.photoCode).fetch(1)
                if p:
                    p[0].status='0'
                    p[0].lastUpdateTime=datetime.now()
                    db.put(p)
                img.delete()
            else:
                img.updataTime=datetime.now()
                img.put()
        except Exception,e:
            img.updataTime=datetime.now()
            img.put()
            logging.error('img-'+str(e)+url)


class RSSManage(PublicPage):
#    def get(self, *args):
#        img=self.request.get('img')
#        Images().get_by_id(int(img)).delete()
    def post(self):
        try:
            fathercode=self.request.get('code')[:-1]
            if fathercode:
                lib=getTmpLib()
                #保存图片
                imgtext=''
                imglist=[]
                photolist=[]
                for i in range(15):
                    name=self.request.get('imgName'+str(i))
                    otherId=self.request.get('img'+str(i))
                    if name and otherId:
        #                image=methods.addImage2(bf,name)
                        otherId=int(otherId)
                        img=Images()
                        img.name=name
                        img.otherId=otherId
                        img.isDown=False
                        img.updataTime=datetime.now()
                        img.put()
                        img.photoCode=str(img.key().id())
                        img.put()
                        photoLib_Photo = PhotoLib_Photo()
                        photoLib_Photo.photoLibCode=str(lib.photoLibCode)
                        photoLib_Photo.photoCode=img.photoCode
                        photoLib_Photo.indexNo = string.atoi(getTimeIndex());
                        photoLib_Photo.status = '1'
                        photoLib_Photo.put()
                        imgtext+='[*TmpImg/'+img.photoCode+'*][()]'#图片在文本中的格式
                        imglist.append(img.key().id())
                        photolist.append(photoLib_Photo.key().id())
                    else:
                        break
                #fathercode=self.request.get('code')[:-1]
#                conlist=db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1  ORDER BY code desc",fathercode).fetch(1)
#                if len(conlist)==1:
#                    prev=conlist[0].code
#                else:
#                    prev=''
#                code=AutoCode(fathercode,prev,'')
                rcode=self.request.get('rcode')
                content=ContentClass()
                if rcode:
                    content.code=fathercode+'-'+rcode
                content.maincode='a1'
                content.content=self.request.get('title')
                content.father=fathercode
                content.level=str(len(fathercode.split('-'))+1)
                content.updateSpanTime='100'
                content.status='1'

                content.put()
                if not rcode:
                    content.code=fathercode+'-'+str(content.key().id())
                    content.put()
                replyContent = ReplyContent()
                replyContent.maincode = 'a1'#主编号
                replyContent.code = content.code+'-s01'#编号
                replyContent.father = content.code#父级
                replyContent.imglist=imglist
                replyContent.photolist=photolist
                replyContent.content = imgtext+self.request.get('content').replace('\r\n','[()]').replace('\n','[()]').replace('[()][()]','[()]').replace('[()][()]','[()]')#内容
                replyContent.replyType = '3'
                replyContent.status = '1'
                replyContent.level='100'
                replyContent.put()

                self.response.out.write( content.code.encode('utf-8'))
            else:
                delcodelist=[]
                for i in range(10):
                    delc=self.request.get('deletecode'+str(i))
                    if delc:
                        delcodelist.append(delc)
                logging.info('delete '+str(len(delcodelist)))
                delcontent=ContentClass().all().filter('level =','4').filter('maincode =','a1').filter('code in',delcodelist).fetch(10)
                delReplyContent=ReplyContent().all().filter('level =','100').filter('maincode =','a1').filter('father in',delcodelist).fetch(10)
                logging.info('delete news'+str(len(delcodelist)))
                for dc in delReplyContent:
                    if dc.photolist:
                        piclist=PhotoLib_Photo.get_by_id(dc.photolist)
                        db.delete(filterNone(Images.get_by_id(dc.imglist)))
                        for pic in piclist:
                            if pic:
                                pic.status='0'
                                pic.lastUpdateTime=datetime.now()
                                db.put(pic)
                    else:
                        for img in re.findall('(?i)\[\*TmpImg\/(\d+)\*\]',dc.content.replace('\n','').replace('\r','')):
                            pic=PhotoLib_Photo().all().filter('photoCode',str(img)).fetch(1)
                            if pic:
                                pic[0].status='0'
                                pic[0].lastUpdateTime=datetime.now()
                                db.put(pic)
                            tupian=Images().get_by_id(int(img))
                            if tupian:
                                tupian.delete()
                for delc in delcontent:
                    delc.status='0'
                    delc.lastUpdateTime=datetime.now()
                db.put(delcontent)
                db.delete(delReplyContent)
                self.response.out.write('0')
        except  Exception,e:
            logging.error('0000'+str(e))
            self.error(404)
